package co.pushmall.modules.shop.service.impl;

import cn.hutool.core.util.NumberUtil;
import co.pushmall.modules.shop.domain.PushMallUser;
import co.pushmall.modules.shop.domain.PushMallUserBill;
import co.pushmall.modules.shop.repository.PushMallUserRepository;
import co.pushmall.modules.shop.service.PushMallUserBillService;
import co.pushmall.modules.shop.service.PushMallUserService;
import co.pushmall.modules.shop.service.dto.UserMoneyDTO;
import co.pushmall.modules.shop.service.dto.PushMallUserDTO;
import co.pushmall.modules.shop.service.dto.PushMallUserQueryCriteria;
import co.pushmall.modules.shop.service.mapper.PushMallUserMapper;
import co.pushmall.utils.OrderUtil;
import co.pushmall.utils.PageUtil;
import co.pushmall.utils.QueryHelp;
import co.pushmall.utils.ValidationUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author pushmall
 * @date 2019-10-06
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class PushMallUserServiceImpl implements PushMallUserService {

    private final PushMallUserRepository pushMallUserRepository;

    private final PushMallUserMapper pushMallUserMapper;

    private final PushMallUserBillService pushMallUserBillService;

    public PushMallUserServiceImpl(PushMallUserRepository pushMallUserRepository, PushMallUserMapper pushMallUserMapper, PushMallUserBillService pushMallUserBillService) {
        this.pushMallUserRepository = pushMallUserRepository;
        this.pushMallUserMapper = pushMallUserMapper;
        this.pushMallUserBillService = pushMallUserBillService;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateMoney(UserMoneyDTO param) {
        PushMallUserDTO userDTO = findById(param.getUid());
        Double newMoney = 0d;
        String mark = "";
        String type = "system_add";
        Integer pm = 1;
        String title = "系统增加余额";
        if (param.getPtype() == 1) {
            mark = "系统增加了" + param.getMoney() + "余额";
            newMoney = NumberUtil.add(userDTO.getNowMoney(), param.getMoney()).doubleValue();
        } else {
            title = "系统减少余额";
            mark = "系统扣除了" + param.getMoney() + "余额";
            type = "system_sub";
            pm = 0;
            newMoney = NumberUtil.sub(userDTO.getNowMoney(), param.getMoney()).doubleValue();
            if (newMoney < 0) {
                newMoney = 0d;
            }

        }
        PushMallUser user = new PushMallUser();
        user.setUid(userDTO.getUid());
        user.setNowMoney(BigDecimal.valueOf(newMoney));
        update(user);

        PushMallUserBill userBill = new PushMallUserBill();
        userBill.setUid(userDTO.getUid());
        userBill.setLinkId("0");
        userBill.setPm(pm);
        userBill.setTitle(title);
        userBill.setCategory("now_money");
        userBill.setType(type);
        userBill.setNumber(BigDecimal.valueOf(param.getMoney()));
        userBill.setBalance(BigDecimal.valueOf(newMoney));
        userBill.setMark(mark);
        userBill.setAddTime(OrderUtil.getSecondTimestampTwo());
        userBill.setStatus(1);
        pushMallUserBillService.create(userBill);
    }

    @Override
    public Map<String, Object> queryAll(PushMallUserQueryCriteria criteria, Pageable pageable) {
        Page<PushMallUser> page = pushMallUserRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return PageUtil.toPage(page.map(pushMallUserMapper::toDto));
    }

    @Override
    public List<PushMallUserDTO> queryAll(PushMallUserQueryCriteria criteria) {
        return pushMallUserMapper.toDto(pushMallUserRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    public PushMallUserDTO findById(Integer uid) {
        Optional<PushMallUser> yxUser = pushMallUserRepository.findById(uid);
        //ValidationUtil.isNull(yxUser,"PushMallUser","uid",uid);
        if (yxUser.isPresent()) {
            return pushMallUserMapper.toDto(yxUser.get());
        }
        return new PushMallUserDTO();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PushMallUserDTO create(PushMallUser resources) {
        return pushMallUserMapper.toDto(pushMallUserRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(PushMallUser resources) {
        Optional<PushMallUser> optionalPushMallUser = pushMallUserRepository.findById(resources.getUid());
        ValidationUtil.isNull(optionalPushMallUser, "PushMallUser", "id", resources.getUid());
        PushMallUser pushMallUser = optionalPushMallUser.get();
        pushMallUser.copy(resources);
        pushMallUserRepository.save(pushMallUser);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Integer uid) {
        pushMallUserRepository.deleteById(uid);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void onStatus(Integer uid, Integer status) {
        if (status == 1) {
            status = 0;
        } else {
            status = 1;
        }

        pushMallUserRepository.updateOnstatus(status, uid);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void onIsPass(Integer uid, Integer isPass, Integer applyLevel) {
        pushMallUserRepository.updateOnIsPass(isPass, applyLevel, uid);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void incBrokeragePrice(double price, int uid) {
        pushMallUserRepository.incBrokeragePrice(price, uid);
    }

    @Override
    public List<PushMallUserDTO> findByLevel(Integer id) {
        return pushMallUserMapper.toDto(pushMallUserRepository.findByLevel(id));
    }

}
